package com.sk.sourcecircle.activity.home.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dyhdyh.widget.loading.dialog.LoadingDialog;
import com.jude.rollviewpager.hintview.IconHintView;
import com.sk.sourcecircle.R;
import com.sk.sourcecircle.activity.find.act.TaskDetailsActivity;
import com.sk.sourcecircle.activity.home.activity.AblumDetailsActivity;
import com.sk.sourcecircle.activity.home.activity.DetailsOfConsultationActivity;
import com.sk.sourcecircle.activity.home.activity.EventDetailsActivity;
import com.sk.sourcecircle.activity.home.activity.LocalAblumActivity;
import com.sk.sourcecircle.activity.home.activity.LocalMoreConsultActivity;
import com.sk.sourcecircle.activity.home.activity.LocalMoreTaskAndEventAct;
import com.sk.sourcecircle.activity.login.LoginActivity;
import com.sk.sourcecircle.adapter.AblumListAdapter;
import com.sk.sourcecircle.adapter.BannerAdapter;
import com.sk.sourcecircle.adapter.HomeConsultAdapter;
import com.sk.sourcecircle.adapter.LocalEventAdapter;
import com.sk.sourcecircle.adapter.LocalTaskAdapter;
import com.sk.sourcecircle.app.MyApplication;
import com.sk.sourcecircle.base.BaseFragment;
import com.sk.sourcecircle.callback.HandleDataCallBack;
import com.sk.sourcecircle.callback.MyCallBack;
import com.sk.sourcecircle.dialog.CommentDialogFragment;
import com.sk.sourcecircle.dialog.TipDialogFragment;
import com.sk.sourcecircle.entity.AlbumaBean;
import com.sk.sourcecircle.entity.HomeBannerBean;
import com.sk.sourcecircle.entity.HomeTabList;
import com.sk.sourcecircle.entity.LocalDataBean;
import com.sk.sourcecircle.utils.AppApi;
import com.sk.sourcecircle.utils.MyUtils;
import com.sk.sourcecircle.utils.SnackUtils;
import com.sk.sourcecircle.utils.UIUtils;
import com.sk.sourcecircle.view.FixedProportionViewPager;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.Unbinder;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;

/**
 * Created by sk on 2017/12/11.
 */

public class LocalFragment extends BaseFragment implements HandleDataCallBack, BaseQuickAdapter.OnItemClickListener, BaseQuickAdapter.OnItemChildClickListener {
    @BindView(R.id.line1)
    View line1;
    @BindView(R.id.more_list)
    TextView moreList;
    @BindView(R.id.more_consultation)
    RelativeLayout moreConsultation;
    @BindView(R.id.consult_ryc)
    RecyclerView consultRyc;
    @BindView(R.id.line2)
    View line2;
    @BindView(R.id.more_event)
    RelativeLayout moreEvent;
    @BindView(R.id.event_ryc)
    RecyclerView eventRyc;
    @BindView(R.id.line3)
    View line3;
    @BindView(R.id.more_task)
    RelativeLayout moreTask;
    @BindView(R.id.task_ryc)
    RecyclerView taskRyc;
    @BindView(R.id.line4)
    View line4;
    @BindView(R.id.more_share)
    RelativeLayout moreShare;
    @BindView(R.id.share_ryc)
    RecyclerView shareRyc;
    @BindView(R.id.my_pager)
    FixedProportionViewPager myPager;
    HomeTabList.DataBean dataBean;
    @BindView(R.id.scrollView)
    ScrollView scrollView;
    Unbinder unbinder;
    @BindView(R.id.mPtrFrameLayout)
    PtrClassicFrameLayout mPtrFrameLayout;
    Unbinder unbinder1;

    private HomeConsultAdapter consultAdapter;
    private LocalEventAdapter eventAdapter;
    private LocalTaskAdapter taskAdapter;
    private AblumListAdapter ablumAdapter;

    private List<LocalDataBean.DataBean.ArticleBean> articleBeanList = new ArrayList<>();
    private List<LocalDataBean.DataBean.ActivityBean> activityBeanList = new ArrayList<>();
    private List<LocalDataBean.DataBean.MissionBean> missionBeanList = new ArrayList<>();
    private List<AlbumaBean> albumaBeanList = new ArrayList<>();
    private int pos;
    private LoadingDialog loadingDialog;
    private int seletId;
    private String comment = "";

    private boolean isRefresh = false;

    private MyCallBack callBack;

    public MyCallBack getCallBack() {
        return callBack;
    }

    public void setCallBack(MyCallBack callBack) {
        this.callBack = callBack;
    }


    public static LocalFragment newInstance(HomeTabList.DataBean dataBean) {
        Bundle args = new Bundle();
        args.putParcelable("data", dataBean);
        LocalFragment fragment = new LocalFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    protected int getContentView() {
        return R.layout.fragment_local;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        mPtrFrameLayout.disableWhenHorizontalMove(true);

        mPtrFrameLayout.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, scrollView, header);
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                isRefresh = true;
                doRefresh();
            }
        });

        loadingDialog = MyUtils.getLoadingDialog(mContext, false);

        initRyc();

        myPager.setHintView(new IconHintView(mContext, R.drawable.point_focus, R.drawable.point_normal, UIUtils.dip2px(mContext, 16)));

        dataBean = getArguments().getParcelable("data");
        if (dataBean != null) {
            AppApi.getHomeBanner(String.valueOf(dataBean.getCate_id()), MyApplication.getInstance().getCityId(), null, LocalFragment.this, 0, getActivity());
            Log.v("onViewCreated", MyApplication.getInstance().getCityId());
            AppApi.getNativeData(Integer.parseInt(MyApplication.getInstance().getCityId()), this, 10, getActivity());
        }
    }

    private void initRyc() {

        LinearLayoutManager layoutManager1 = new LinearLayoutManager(mContext);
        LinearLayoutManager layoutManager2 = new LinearLayoutManager(mContext);
        LinearLayoutManager layoutManager3 = new LinearLayoutManager(mContext);
        LinearLayoutManager layoutManager4 = new LinearLayoutManager(mContext);

        layoutManager1.setSmoothScrollbarEnabled(true);
        layoutManager1.setAutoMeasureEnabled(true);

        layoutManager2.setSmoothScrollbarEnabled(true);
        layoutManager2.setAutoMeasureEnabled(true);

        layoutManager3.setSmoothScrollbarEnabled(true);
        layoutManager3.setAutoMeasureEnabled(true);

        layoutManager4.setSmoothScrollbarEnabled(true);
        layoutManager4.setAutoMeasureEnabled(true);


        consultRyc.setLayoutManager(new LinearLayoutManager(mContext));
        consultAdapter = new HomeConsultAdapter(R.layout.item_local_article, articleBeanList);
        consultRyc.setAdapter(consultAdapter);
        View emptyView1 = getLayoutInflater().inflate(R.layout.empty_view, null);
        consultAdapter.setEmptyView(emptyView1);
        consultAdapter.setOnItemClickListener(this);


        eventRyc.setLayoutManager(new LinearLayoutManager(mContext));
        eventAdapter = new LocalEventAdapter(R.layout.item_recommend_event, activityBeanList);
        eventRyc.setAdapter(eventAdapter);
        View emptyView2 = getLayoutInflater().inflate(R.layout.empty_view, null);
        eventAdapter.setEmptyView(emptyView2);
        eventAdapter.setOnItemClickListener(this);

        taskRyc.setLayoutManager(new LinearLayoutManager(mContext));
        taskAdapter = new LocalTaskAdapter(R.layout.item_recommend_event, missionBeanList);
        taskRyc.setAdapter(taskAdapter);
        View emptyView3 = getLayoutInflater().inflate(R.layout.empty_view, null);
        taskAdapter.setEmptyView(emptyView3);
        taskAdapter.setOnItemClickListener(this);

        shareRyc.setLayoutManager(new LinearLayoutManager(mContext));
        ablumAdapter = new AblumListAdapter(R.layout.item_album, albumaBeanList);
        shareRyc.setAdapter(ablumAdapter);
        View emptyView4 = getLayoutInflater().inflate(R.layout.empty_view, null);
        ablumAdapter.setEmptyView(emptyView4);
        ablumAdapter.setOnItemClickListener(this);
        ablumAdapter.setOnItemChildClickListener(this);


        consultRyc.setHasFixedSize(true);
        consultRyc.setNestedScrollingEnabled(false);

        eventRyc.setHasFixedSize(true);
        eventRyc.setNestedScrollingEnabled(false);

        taskRyc.setHasFixedSize(true);
        taskRyc.setNestedScrollingEnabled(false);

        shareRyc.setHasFixedSize(true);
        shareRyc.setNestedScrollingEnabled(false);

    }

    @OnClick({R.id.more_consultation, R.id.more_event, R.id.more_task, R.id.more_share})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.more_consultation:
                Intent consultIntent = new Intent(mContext, LocalMoreConsultActivity.class);
                consultIntent.putExtra("cate_id", dataBean.getCate_id());
                startActivity(consultIntent);
                break;
            case R.id.more_event:
                Intent eventIntent = new Intent(mContext, LocalMoreTaskAndEventAct.class);
                eventIntent.putExtra("id", dataBean.getCate_id());
                eventIntent.putExtra("type", 0);
                startActivity(eventIntent);
                break;
            case R.id.more_task:
                Intent taskEvent = new Intent(mContext, LocalMoreTaskAndEventAct.class);
                taskEvent.putExtra("id", dataBean.getCate_id());
                taskEvent.putExtra("type", 1);
                startActivity(taskEvent);
                break;
            case R.id.more_share:
                Intent intent = new Intent(mContext, LocalAblumActivity.class);
                startActivity(intent);
                break;
        }
    }

    @Override
    public void handlerSuccessData(String result, int tag) {
        loadingDialog.cancelDialog();
        switch (tag) {
            case 0:
                HomeBannerBean homeBannerBean = JSON.parseObject(result, HomeBannerBean.class);
                List<HomeBannerBean.DataBean> bannerList = homeBannerBean.getData();
                initBanner(bannerList);
                break;
            case 10:

                if (isRefresh) {
                    isRefresh = false;
                    mPtrFrameLayout.refreshComplete();
                }

                LocalDataBean localDataBean = JSON.parseObject(result, LocalDataBean.class);
                List<LocalDataBean.DataBean.ActivityBean> activityBeans = localDataBean.getData().getActivity();
                List<LocalDataBean.DataBean.ArticleBean> articleBeans = localDataBean.getData().getArticle();
                List<LocalDataBean.DataBean.MissionBean> missionBeans = localDataBean.getData().getMission();
                List<AlbumaBean> albumaBeans = localDataBean.getData().getAlbuma();

                articleBeanList.clear();
                activityBeanList.clear();
                missionBeanList.clear();
                albumaBeanList.clear();

                articleBeanList.addAll(articleBeans);
                activityBeanList.addAll(activityBeans);
                missionBeanList.addAll(missionBeans);
                albumaBeanList.addAll(albumaBeans);

                consultAdapter.notifyDataSetChanged();
                eventAdapter.notifyDataSetChanged();
                taskAdapter.notifyDataSetChanged();
                ablumAdapter.notifyDataSetChanged();
                break;
            case 1:
                Toast.makeText(mContext, "评论发布成功！", Toast.LENGTH_SHORT).show();
                AlbumaBean.DetailBean.ReplyBean replyBean = new AlbumaBean.DetailBean.ReplyBean();
                replyBean.setContent(comment);
                replyBean.setType("reply");
                replyBean.setNickname(MyUtils.getUser(mContext).getNickname());
                albumaBeanList.get(pos).getDetail().getReply().add(replyBean);
                ablumAdapter.notifyItemChanged(pos);
                break;
            case 6:
                Toast.makeText(mContext, "相册收藏成功！", Toast.LENGTH_SHORT).show();
                albumaBeanList.get(pos).getDetail().setIs_favorite(1);
                ablumAdapter.notifyItemChanged(pos);
                break;
            case 2:
                Toast.makeText(mContext, "点赞成功！", Toast.LENGTH_SHORT).show();
                AlbumaBean.DetailBean.ReplyBean praiseBean = new AlbumaBean.DetailBean.ReplyBean();
                praiseBean.setType("dig");
                praiseBean.setNickname(MyUtils.getName(mContext));
                albumaBeanList.get(pos).getDetail().getReply().add(praiseBean);
                albumaBeanList.get(pos).getDetail().setIs_dig(1);
                ablumAdapter.notifyItemChanged(pos);
                break;
            case 4:
                Toast.makeText(mContext, "请求发送成功，请等待回复！", Toast.LENGTH_SHORT).show();
                break;
            case 16:
                SnackUtils.show(mRootView, "相册删除成功！");
                albumaBeanList.remove(pos);
                ablumAdapter.notifyDataSetChanged();
                break;

        }
    }

    @Override
    public void handlerFailData(String failString, int tag) {
        loadingDialog.cancelDialog();
    }

    @Override
    public void handleErrorData(String error, int tag) {
        loadingDialog.cancelDialog();
    }

    private void initBanner(List<HomeBannerBean.DataBean> bannerList) {
        BannerAdapter adapter = new BannerAdapter(bannerList, mContext);
        myPager.setAdapter(adapter);
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        if (adapter instanceof HomeConsultAdapter) {

            Intent intent = new Intent(mContext, DetailsOfConsultationActivity.class);
            intent.putExtra("id", articleBeanList.get(position).getArticle_id());
            startActivity(intent);
            int show = articleBeanList.get(position).getShow();
            articleBeanList.get(position).setShow(show+1);
            consultAdapter.notifyItemChanged(position);

        } else if (adapter instanceof LocalEventAdapter) {

            Intent intent = new Intent(mContext, EventDetailsActivity.class);
            intent.putExtra("id", activityBeanList.get(position).getActivity_id());
            startActivity(intent);

        } else if (adapter instanceof LocalTaskAdapter) {

            Intent intent = new Intent(mContext, TaskDetailsActivity.class);
            intent.putExtra("id", missionBeanList.get(position).getActivity_id());
            startActivity(intent);

        } else if (adapter instanceof AblumListAdapter) {
            if (MyUtils.getToken(mContext) != null && MyUtils.getToken(mContext).length() == 0) {
                Toast.makeText(mContext, "您尚未登陆，请先登录！", Toast.LENGTH_SHORT).show();
                Intent loginIntent = new Intent(mContext, LoginActivity.class);
                startActivityForResult(loginIntent, 200);
                return;
            }
            Intent intent = new Intent(mContext, AblumDetailsActivity.class);
            intent.putExtra("data", albumaBeanList.get(position));
            startActivity(intent);
        }
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        pos = position;
        switch (view.getId()) {
            case R.id.comment:

                if (MyUtils.getToken(mContext) != null && MyUtils.getToken(mContext).length() == 0) {
                    Toast.makeText(mContext, "您尚未登陆，请先登录！", Toast.LENGTH_SHORT).show();
                    Intent loginIntent = new Intent(mContext, LoginActivity.class);
                    startActivityForResult(loginIntent, 200);
                    return;
                }

                seletId = albumaBeanList.get(position).getAlbum_id();
                CommentDialogFragment commentDialogFragment = new CommentDialogFragment();
                commentDialogFragment.setCallBack(LocalFragment.this);
                if (albumaBeanList.get(position).getDetail().getIs_favorite() == 1) {
                    commentDialogFragment.setCollect(true);
                } else {
                    commentDialogFragment.setCollect(false);
                }
                commentDialogFragment.show(getActivity().getSupportFragmentManager(), "comment");
                break;
            case R.id.add_praise:

                if (MyUtils.getToken(mContext) != null && MyUtils.getToken(mContext).length() == 0) {
                    Toast.makeText(mContext, "您尚未登陆，请先登录！", Toast.LENGTH_SHORT).show();
                    Intent loginIntent = new Intent(mContext, LoginActivity.class);
                    startActivityForResult(loginIntent, 200);
                    return;
                }

                loadingDialog.show();
                seletId = albumaBeanList.get(position).getAlbum_id();
                AppApi.praiseAlbum(albumaBeanList.get(position).getAlbum_id(), LocalFragment.this, 2, getActivity());
            case R.id.cancel_praise:
                break;
            case R.id.add_care:

                if (MyUtils.getToken(mContext) != null && MyUtils.getToken(mContext).length() == 0) {
                    Toast.makeText(mContext, "您尚未登陆，请先登录！", Toast.LENGTH_SHORT).show();
                    Intent loginIntent = new Intent(mContext, LoginActivity.class);
                    startActivityForResult(loginIntent, 200);
                    return;
                }

                loadingDialog.show();
                AppApi.addFriend(albumaBeanList.get(position).getUser_id(), LocalFragment.this, 4, getActivity());
                break;
            case R.id.cancel_care:
                break;
            case R.id.more:
                albumaBeanList.get(position).setExpand(true);
                adapter.notifyItemChanged(position);
                break;
            case R.id.tv_delete:
                final int id = albumaBeanList.get(position).getAlbum_id();
                TipDialogFragment tipDialogFragment = new TipDialogFragment();
                tipDialogFragment.setMyCallBack(new MyCallBack() {
                    @Override
                    public void releaseAlbum() {

                    }

                    @Override
                    public void joinGroup() {

                    }

                    @Override
                    public void takePhoto() {

                    }

                    @Override
                    public void choosePhoto() {

                    }

                    @Override
                    public void sure() {
                        loadingDialog.show();
                        AppApi.deleteAblumn(id, LocalFragment.this, 16, getActivity());
                    }

                    @Override
                    public void cancelOder(String string) {

                    }

                    @Override
                    public void chooseGroup(String id) {

                    }

                    @Override
                    public void cancel() {

                    }

                    @Override
                    public void sendText(String comment) {

                    }
                });
                tipDialogFragment.setContent("确认删除该相册？");
                tipDialogFragment.show(getChildFragmentManager(), "delete");
                break;
        }
    }

    @Override
    public void sendText(String comment) {
        super.sendText(comment);
        loadingDialog.show();
        this.comment = comment;
        AppApi.commentAlbum(seletId, comment, LocalFragment.this, 1, getActivity());
    }

    @Override
    public void sure() {
        super.sure();
        loadingDialog.show();
        AppApi.collectAlbum(seletId, LocalFragment.this, 6, getActivity());
    }

    public void doRefresh(int cityId) {
        if(dataBean!=null){
            AppApi.getHomeBanner(String.valueOf(dataBean.getCate_id()), String.valueOf(cityId), null, LocalFragment.this, 0, getActivity());
            AppApi.getNativeData(cityId, this, 10, getActivity());
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == -1) {
            if (requestCode == 200) {
                loadingDialog.show();
                if (dataBean != null) {
                    AppApi.getHomeBanner(String.valueOf(dataBean.getCate_id()), MyApplication.getInstance().getCityId(), null, LocalFragment.this, 0, getActivity());
                    Log.v("onViewCreated", MyApplication.getInstance().getCityId());
                    AppApi.getNativeData(Integer.parseInt(MyApplication.getInstance().getCityId()), this, 10, getActivity());
                }
            }
        }
    }


    public void doRefresh() {
        isRefresh = true;
        AppApi.getHomeBanner(String.valueOf(dataBean.getCate_id()), MyApplication.getInstance().getCityId(), null, LocalFragment.this, 0, getActivity());
        AppApi.getNativeData(Integer.parseInt(MyApplication.getInstance().getCityId()), this, 10, getActivity());
    }

}
